// SteeringSystemCAN.h
#pragma once

#include <cstdint>
#include <string>
#include <array>
#include <random>
#include <chrono>
#include <thread>
#include <sys/socket.h>
#include <net/if.h>
#include <linux/can.h>
#include <linux/can/raw.h>
#include <unistd.h>
#include <cerrno>

// 阈值配置结构体
struct TimingThresholds {
    int64_t output_no_response;    // 无输出阈值(微秒)
    int64_t output_too_fast;      // 输出过快阈值(微秒)
    int64_t output_too_slow;      // 输出过慢阈值(微秒)
    int64_t feedback_normal;      // 反馈正常阈值(微秒)
    int64_t feedback_slow;        // 反馈较慢阈值(微秒)
    int64_t feedback_no_response; // 无反馈阈值(微秒)
};

// 舵角和舵速配置结构体
struct RPMThresholds {
    int16_t min_rpm;            // 最小舵角
    int16_t max_rpm;            // 最大舵角
    bool allow_negative;        // 是否允许负舵角
};

// SteeringSystemCAN 类
class SteeringSystemCAN {
public:
    // 静态方法声明
    static void setTimingThresholds(const TimingThresholds& thresholds);
    static TimingThresholds getCurrentThresholds();
    static void setRPMThresholds(const RPMThresholds& thresholds);
    static RPMThresholds getCurrentRPMThresholds();
    static int checkOutputTiming(int64_t timeInterval);
    static int checkFeedbackTiming(int64_t timeBack);
    static bool checkSteeringAngleAndSpeed(const uint8_t* data, size_t offset, std::string& message);
    static int16_t parseSteeringAngle(const uint8_t* data, size_t offset);
    static float parseSteeringSpeed(const uint8_t* data, size_t offset);
    static uint8_t parseDeployCommand(const uint8_t* data, size_t offset);
    static bool isOverrideEnabled(const uint8_t* data, size_t offset);
    static int checkBusbarVoltage(const uint8_t* data, size_t offset);
    static int checkMotorCurrent(const uint8_t* data, size_t offset);
    static int checkTemperature(const uint8_t* data, size_t offset);
    static int checkFaultBits(const uint8_t* data, size_t offset);

private:
    // 静态成员变量
    static TimingThresholds currentTimingThresholds;
    static RPMThresholds currentRPMThresholds;
};

// SteeringController 类
class SteeringController {
public:
    // 构造函数和析构函数
    SteeringController(const std::string& ifname = "can0");
    ~SteeringController();

    // 方法声明
    int16_t generateRandomSteering();
    int generateRandomInterval();
    void sendSteeringCommand(int16_t steering, bool faultClear = false);
    void run();

private:
    // 私有成员变量
    int sock; // CAN 套接字
    struct sockaddr_can addr;
    struct ifreq ifr;
    std::default_random_engine rng; // 随机数生成器
};